package com.njlime.cms.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.njlime.cms.entities.Information;
import com.njlime.cms.entities.InformationComment;
import com.njlime.cms.entities.Label;
import com.njlime.cms.sdk.weibo4j.util.WeiboConfig;
import com.njlime.cms.service.sys.*;
import com.njlime.core.base.controller.BaseController;
import com.njlime.core.exception.ExceptionState;
import com.njlime.core.helper.GlobalValue;
import com.njlime.core.helper.PageBean;
import com.njlime.core.utils.StringUtil;
import com.njlime.core.web.validation.annotation.support.ValidateService;
import com.njlime.member.entiies.MemberComment;
import com.njlime.sys.entities.ConfigItem;
import com.njlime.sys.entities.Unit;
import com.njlime.sys.entities.UnitWxConfig;
import com.njlime.sys.service.ConfigService;
import com.njlime.sys.service.UnitService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * Created by Dean on 2017/8/9.
 */
@Controller
@RequestMapping(value = "/cms/information")
public class InformationController extends BaseController {
    @Resource
    private InformationService informationService;
    @Resource
    private InformationCommentService informationCommentService;
    @Resource
    private ConfigService configService;
    @Resource
    private LabelService labelService;
    @Resource
    private ChannelService channelService;
    @Resource
    private ColumnService columnService;
    @Resource
    private UnitService unitService;



    //--------------------控制器-------------------------

    /**
     * 跳转热点管理页面
     * @return
     */
    @RequestMapping(value = "infoManage")
    public ModelAndView infoManage(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/sys/content/information/index");
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(Integer.MAX_VALUE);
        modelAndView.addObject("labelList",labelService.list(pageBean, new Label()).getMapList());
        //频道栏目
        Unit rootUnit = getLoginUser().getRootUnit();
        if(rootUnit != null){
            //此处无法判断类型
            modelAndView.addObject("channelList",channelService.getChannelList(rootUnit.getId(),1));
        }
        //一键发布参数
        /*String ttToken = (String)request.getSession().getAttribute("ttToken");
        logger.debug("ttToken:"+ttToken);
        if(rootUnit != null && StringUtil.isEmpty(ttToken)){
            UnitWxConfig config = unitService.getWxConfig(rootUnit.getId());
            if(config != null && config.getTt_key() != null){
                logger.debug("ttKey:"+ config.getTt_key());
                String url = "https://open.snssdk.com/auth/authorize?response_type=code&client_key=" + config.getTt_key()
                        + "&redirect_uri=" + WeiboConfig.getValue("tt_redirect_URI") + "&auth_only=1&display=2&state=4";
                modelAndView.setViewName("redirect:" + url);
            }
        }*/
        return modelAndView;
    }

    /**
     * 跳转热点编辑页面
     * @return
     */
    @RequestMapping(value = "editView")
    public ModelAndView editView(HttpServletRequest request, Integer id) {
        ModelAndView modelAndView = new ModelAndView("/sys/content/information/edit");
        //标签
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(Integer.MAX_VALUE);
        modelAndView.addObject("labelList",labelService.list(pageBean, new Label()).getMapList());
        //资讯详情
        Information information = informationService.findOne(id);
        checkDataPermission(information.getUnit_id(), information.getCreator());
        modelAndView.addObject("info", information);
        //频道栏目
        Unit rootUnit = getLoginUser().getRootUnit();
        modelAndView.addObject("channelList",channelService.getChannelList(rootUnit.getId(),1));
        modelAndView.addObject("colList",columnService.getColumnListByChannelId(information.getChannel_id(),rootUnit.getId()));
        return modelAndView;
    }

    /**
     * 跳转热点新增页面
     * @return
     */
    @RequestMapping(value = "addView")
    public ModelAndView addView(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/sys/content/information/add");
        //标签
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(Integer.MAX_VALUE);
        modelAndView.addObject("labelList",labelService.list(pageBean, new Label()).getMapList());
        //频道栏目
        Unit rootUnit = getLoginUser().getRootUnit();
        modelAndView.addObject("channelList",channelService.getChannelList(rootUnit.getId(),1));
        return modelAndView;
    }

    /**
     * 跳转热点评论页面
     * @return
     */
    @RequestMapping(value = "commentView")
    public ModelAndView commentView(HttpServletRequest request, Integer id) {
        ModelAndView modelAndView = new ModelAndView("/sys/content/information/comment");
        Information information = informationService.findOne(id);
        checkDataPermission(information.getUnit_id(), information.getCreator());
        modelAndView.addObject("info", information);
        return modelAndView;
    }

    //------------------功能--------------------------
    /**
     * 获取热点信息详情
     *
     * @param id
     * @param request
     * @return
     */
    @RequestMapping(value = "info", method = RequestMethod.GET)
    @ResponseBody
    public String info(int id, HttpServletRequest request) {
        Information information = informationService.findOne(id);
        checkDataPermission(information.getUnit_id(), information.getCreator());
        return toJsonSuccessData(informationService.get(id));
    }

    /**
     * 保存
     *
     * @param information
     * @param request
     * @return
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public String save(Information information, HttpServletRequest request, Double charge) {
        try {
            if(!StringUtil.isEmpty(information.getSource_url())){
                information.setContent(information.getSource_url());
            }
            ValidateService.valid(information);
        } catch (Exception e) {
            e.printStackTrace();
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, e.getMessage());
        }
        if (information.getSource_url() != null && !"".equals(information.getSource_url())) {
            if (information.getSource_url().contains("#")) {
                information.setSource_url(information.getSource_url().substring(0, information.getSource_url().indexOf("#")));
            }
        }
        if(information.getType() == null || Information.InfoType.INFO == information.getType()){
            information.setType(Information.InfoType.INFO);
            information.setTopic_id(0);
        }
        if (GlobalValue.NO.equals(information.getIs_charge())) {
            information.setMoney(0);
        }else{
            if(charge == null){
                return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, "请输入付费阅读金额");
            }else{
                charge = charge * 100;
                information.setMoney(charge.intValue());
            }
        }
        information.setCreator(getLoginUser().getId());
        information.setUnit_id(getLoginUserUnitId());
        information.setRoot_unit_id(unitService.getRootUnit(information.getUnit_id()));
        Integer id = informationService.save(information);
        if (id > 0) {
            return toJsonSuccessData();
        } else {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "添加失败");
        }
    }

    /**
     * 編輯
     *
     * @param info
     * @param request
     * @return
     */
    @RequestMapping(value = "edit", method = RequestMethod.POST)
    @ResponseBody
    public String editInfo(Information info, HttpServletRequest request,Double charge) {
        Information information = informationService.findOne(info.getId());
        checkDataPermission(information.getUnit_id(), information.getCreator());
        info.setUnit_id(getLoginUserUnitId());
        if (info.getSource_url() != null && !"".equals(info.getSource_url())) {
            if (info.getSource_url().contains("#")) {
                info.setSource_url(info.getSource_url().substring(0, info.getSource_url().indexOf("#")));
            }
        }
        if (GlobalValue.NO.equals(information.getIs_charge())) {
            info.setMoney(0);
        }else{
            if(charge == null){
                return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, "请输入付费阅读金额");
            }else{
                charge = charge * 100;
                info.setMoney(charge.intValue());
            }
        }
        info.setUpdater(getLoginUser().getId());
        info.setUpdate_time(new Date());
        if (information.getPublish_status() != null && information.getPublish_status() != GlobalValue.PublishStatus.UNPUBLISHED) {//不是定时发送的，则发送时间为当前时间
            information.setPublish_time(new Date());
        }
        int count = informationService.editInfo(info);
        if (count > 0) {
            return toJsonSuccessData();
        } else {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "更新失败");
        }
    }

    /**
     * 刪除
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public String informationDel(HttpServletRequest request, Integer id) {
        Information information = informationService.findOne(id);
        checkDataPermission(information.getUnit_id(), information.getCreator());
        int count = informationService.del(id);
        if (count > 0) {
            return toJsonSuccessData();
        } else {
            return toJsonErrorData(ExceptionState.PARAM_EXCEPTION, "删除失败");
        }
    }

    /**
     * 评论开关
     *
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "toggleComment", method = RequestMethod.POST)
    @ResponseBody
    public String toggleComment(HttpServletRequest request, Integer id) {
        Information information = informationService.findOne(id);
        checkDataPermission(information.getUnit_id(), information.getCreator());
        int count = informationService.toggleComment(id);
        if (count > 0) {
            return toJsonSuccessData();
        } else {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "操作失败");
        }
    }

    /**
     * 上下线
     *
     * @param request
     * @param info
     * @return
     */
    @RequestMapping(value = "togglePublish", method = RequestMethod.POST)
    @ResponseBody
    public String togglePublish(HttpServletRequest request, Information info) {
        Information information = informationService.findOne(info.getId());
        checkDataPermission(information.getUnit_id(), information.getCreator());
        int count = informationService.togglePublish(info);
        if (count > 0) {
            return toJsonSuccessData();
        } else {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "操作失败");
        }
    }

    /**
     * 获取热点列表
     *
     * @param pageBean
     * @param information
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(PageBean pageBean, Information information, HttpServletRequest request) {
        return toJsonListData(informationService.list(pageBean, information, false));
    }

    /**
     * 获取阅读包月金额
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getMonthCharge", method = RequestMethod.GET)
    public String getMonthCharge(HttpServletRequest request) {
        Unit unit = getLoginUser().getRootUnit();
        if (unit != null) {
            if(!unit.getId().equals(getLoginUserUnitId())){
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION,"越权操作");
            }
            ConfigItem configItem = configService.getByName("info_month_charge", unit.getId());
            return toJsonSuccessData(configItem);
        }else{
            return toJsonErrorData(ExceptionState.MANAGER_EXCEPTION);
        }
    }

    /**
     * 更新阅读包月金额
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateMonthCharge")
    public String updateMonthCharge(HttpServletRequest request, Double charge) {
        Unit unit = getLoginUser().getRootUnit();
        if (unit != null) {
            if(!unit.getId().equals(getLoginUserUnitId())){
                return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION,"越权操作");
            }
            charge = charge * 100;
            configService.updateByName("info_month_charge", charge.intValue() + "", unit.getId());
            return toJsonSuccessData();
        }else{
            return toJsonErrorData(ExceptionState.MANAGER_EXCEPTION);
        }

    }


    /**
     * 文章评论详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "commentInfo", method = RequestMethod.GET)
    @ResponseBody
    public String commentInfo(int id) {
        InformationComment comment = informationCommentService.findOne(id);
        Information information = informationService.findOne(comment.getInformation_id());
        checkDataPermission(information.getUnit_id(), information.getCreator());
        return toJsonSuccessData(comment);
    }

    /**
     * 回复
     *
     * @param reply
     * @return
     */
    @RequestMapping(value = "commentReply", method = RequestMethod.POST)
    @ResponseBody
    public String commentReply(String reply, HttpServletRequest request, InformationComment comment) {
        Information information = informationService.findOne(comment.getInformation_id());
        checkDataPermission(information.getUnit_id(), information.getCreator());
        informationCommentService.reply(comment.getId(), reply);
        return toJsonSuccessData();
    }

    /**
     * 审核
     *
     * @param id 文章id
     * @return
     */
    @RequestMapping(value = "commentAudit", method = RequestMethod.POST)
    @ResponseBody
    public String commentAudit(int id) {
        InformationComment comment = informationCommentService.findOne(id);
        Information information = informationService.findOne(comment.getInformation_id());
        checkDataPermission(information.getUnit_id(), information.getCreator());
        MemberComment memberComment = new MemberComment();
        memberComment.setMember_id(comment.getUser_id());
        memberComment.setBusiness_id(comment.getInformation_id());
        memberComment.setBusiness_type(GlobalValue.BusinessType.INFORMATION);
        memberComment.setBusiness_title(information.getTitle());
        memberComment.setCreate_time(new Date());
        informationCommentService.auditComment(comment, memberComment);
        return toJsonSuccessData();
    }

    /**
     * 删除 文章评论
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "commentDel", method = RequestMethod.POST)
    @ResponseBody
    public String commentDel(HttpServletRequest request, InformationComment comment) {
        Information information = informationService.findOne(comment.getInformation_id());
        checkDataPermission(information.getUnit_id(), information.getCreator());
        int count = informationCommentService.del(comment);
        if (count > 0) {
            return toJsonSuccessData();
        } else {
            return toJsonErrorData(ExceptionState.BUSINESS_EXCEPTION, "删除失败");
        }
    }

    /**
     * 评论置顶
     *
     * @param comment 评论
     * @return
     */
    @RequestMapping(value = "commentTop", method = RequestMethod.POST)
    @ResponseBody
    public String commentTop(InformationComment comment) {
        Information information = informationService.findOne(comment.getInformation_id());
        checkDataPermission(information.getUnit_id(), information.getCreator());
        informationCommentService.top(comment.getId());
        return toJsonSuccessData();
    }


    /**
     * 文章评论点赞数  +1
     *
     * @param id 文章id
     * @return
     */
    @RequestMapping(value = "commentFabulous", method = RequestMethod.POST)
    @ResponseBody
    public String commentFabulous(int id) {
        InformationComment comment = informationCommentService.findOne(id);
        Information information = informationService.findOne(comment.getInformation_id());
        checkDataPermission(information.getUnit_id(), information.getCreator());
        informationCommentService.like(id);
        return toJsonSuccessData();
    }

    /**
     * 文章评论列表获取
     *
     * @param pageBean
     * @param comment
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "commentList", method = RequestMethod.GET)
    public String list(PageBean pageBean, InformationComment comment, HttpServletRequest request) {
        Information information = informationService.findOne(comment.getInformation_id());
        checkDataPermission(information.getUnit_id(), information.getCreator());
        return toJsonListData(informationCommentService.list(pageBean, comment));
    }



}
